using System;
using System.Collections.Generic;
using System.Data;
using System.Threading.Tasks;
using System.Windows.Forms;
using CloudApiServer.Class;
using MySql.Data.MySqlClient;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace CloudApiServer.Services;

/// <summary>
/// 药店结算公共服务
/// </summary>
public class DrugStoreCommonService
{
    /// <summary>
    /// 查询参保人信息条数
    /// </summary>
    /// <param name="psn_no"></param>
    /// <returns></returns>
    public async Task<DataTable> FetchPersonInfo(string psn_no)
    {
        string connectionString = $"Database={ApiDatainfo.mysqlDatabase};Data Source={ApiDatainfo.mysqlUrl};Port={ApiDatainfo.mysqlPost};UserId={ApiDatainfo.mysqlUser};Password={ApiDatainfo.mysqlPwd};Charset=utf8mb4;TreatTinyAsBoolean=false;Allow User Variables=True";
        var query = "select * from fsi_PsnInfo where psn_no=@psn_no";
        var parameters = new List<MySqlParameter>
        {
            new MySqlParameter("@psn_no", psn_no),
        };
        return await MySqlHelper.ExecuteQueryAsync(connectionString, query, parameters);
    }
    
    public string SerializeZheJiangExtendedFields(double clcYearAcctPay,double Q0001,double crtYearAcctPay )
    { 
        SetlinfoexpcontentZJ setlinfoexpcontent = new SetlinfoexpcontentZJ
        {
            clcYearAcctPay = clcYearAcctPay,
            Q0001 = Q0001,
            crtYearAcctPay = crtYearAcctPay
        };
        return  JsonConvert.SerializeObject(setlinfoexpcontent);
    }
    public string SerializeShanXiExtendedFields(string psninfo_expcontent,double medIns_wallet_pay )
    {
        if (!string.IsNullOrEmpty(psninfo_expcontent))
        {
            JObject obj = JObject.Parse(psninfo_expcontent);
            if (obj.TryGetValue("medIns_wallet_balance", out JToken balanceToken))
            {
                Setlinfoexpcontent setlinfoexpcontent = new Setlinfoexpcontent
                {
                    medIns_wallet_balance = balanceToken.Value<double>() - medIns_wallet_pay,
                    medIns_wallet_pay = medIns_wallet_pay
                };
                return JsonConvert.SerializeObject(setlinfoexpcontent);
            }
        }
        return null;
    }
    
    public string GetDrugStoreClrType(string medType)
    {           
        //清算类型 如果传入的是定点购药41 则清算类型为41药店，否则统一为11 门诊（不区分住院外配归到住院的部分）
        return medType switch
        { 
            "41"=> "41",
            _ => "11"
        };
    }
    
    /// <summary>
    /// 新增历史购药明细（浙江省ZJ3100）
    /// </summary>
    /// <param name="drug">药品入参</param>
    /// <param name="transaction">事务</param>
    /// <returns></returns>
    public async Task<bool> InsertQuerydrugdosag(FsiQuerydrugdosagInsert drug, MySqlTransaction transaction = null)
    {
        string connectionString =
            $"Database={ApiDatainfo.mysqlDatabase};Data Source={ApiDatainfo.mysqlUrl};Port={ApiDatainfo.mysqlPost};UserId={ApiDatainfo.mysqlUser};Password={ApiDatainfo.mysqlPwd};Charset=utf8mb4;TreatTinyAsBoolean=false;Allow User Variables=True";
        try
        {
            string query;
            string listType;
            string medChrgitmType;
            if (drug.hilistCode.StartsWith("X"))
            {
                listType = "101";
                medChrgitmType = "09";
            }
            else if (drug.hilistCode.StartsWith("Z"))
            {
                listType = "101";
                medChrgitmType = "11";
            }
            else if (drug.hilistCode.StartsWith("T"))
            {
                listType = "102";
                medChrgitmType = "10";
            }
            else if (drug.hilistCode.StartsWith("Q02") || drug.hilistCode.StartsWith("C"))
            {
                listType = "301";
                medChrgitmType = "08";
            }
            else
            {
                listType = "";
                medChrgitmType = "14";
            }

            query =
                "INSERT INTO `fsi_querydrugdosag` ( `mdtrtId`, `feeOcurTime`, `hiListCode`, `cnt`, `sinDosDscr`, `usedFrquDscr`, `psnno`, `fixmedins_code`, `fixmedins_name`, `create_time`, `update_time`," +
                " `listType`, `medinsListCodg`, `medinsListName`, `medChrgitmType`, `chrgitmLv`, `pric`, `detItemFeeSumamt`, `inscpAmt`, `bilgDrCode`, `bilgDrName`, `ds`) " +
                " VALUES ( @mdtrtId, @feeOcurTime, @hiListCode,@cnt,@sinDosDscr,@usedFrquDscr,@psnno,@fixmedins_code, @fixmedins_name, now(), now()," +
                " @listType, @medinsListCodg, @medinsListName, @medChrgitmType, @chrgitmLv, @pric, @detItemFeeSumamt, @inscpAmt, @bilgDrCode, @bilgDrName, @ds);";
            var parameters = new List<MySqlParameter>
            {
                new MySqlParameter("@mdtrtId", drug.mdtrtId),
                new MySqlParameter("@feeOcurTime", drug.feeOcurTime),
                new MySqlParameter("@hiListCode", drug.hilistCode),
                new MySqlParameter("@cnt", drug.cnt),
                new MySqlParameter("@sinDosDscr", drug.sinDosDscr),
                new MySqlParameter("@usedFrquDscr", drug.usedFrquDscr),
                new MySqlParameter("@psnno", drug.psnno),
                new MySqlParameter("@fixmedins_code", drug.fixmedins_code),
                new MySqlParameter("@fixmedins_name", drug.fixmedins_name),
                new MySqlParameter("@listType", listType),
                new MySqlParameter("@medinsListCodg", drug.medinsListCodg),
                new MySqlParameter("@medinsListName", drug.medinsListName),
                new MySqlParameter("@medChrgitmType", medChrgitmType),
                new MySqlParameter("@chrgitmLv", drug.chrgitmLv),
                new MySqlParameter("@pric", drug.pric),
                new MySqlParameter("@detItemFeeSumamt", drug.detItemFeeSumamt),
                new MySqlParameter("@inscpAmt", drug.inscpAmt),
                new MySqlParameter("@bilgDrCode", drug.bilgDrCode),
                new MySqlParameter("@bilgDrName", drug.bilgDrName),
                new MySqlParameter("@ds", drug.ds)
            };
            await MySqlHelper.ExecuteNonQueryAsync(connectionString, query, parameters, transaction);
            return true;
        }
        catch (Exception ex)
        {
            LogHelper.Error(
                $"[DrugStoreCommonService.InsertQuerydrugdosag]历史费用明细记录新增异常，错误内容：{ex.Message} 异常堆栈{ex.StackTrace}");
            throw;
        }
    }
    /// <summary>
    /// 药品处方验证
    /// </summary>
    /// <param name="rxno">处方编号</param>
    /// <param name="med_type">医疗类别</param>
    /// <param name="med_list_codg">国家编码</param>
    /// <returns></returns>
    /// <exception cref="Exception"></exception>
    public async Task<bool> VerifyPrescriptionDrugs(string rxno, string med_type, string med_list_codg)
    {
        string connectionString =
            $"Database={ApiDatainfo.mysqlDatabase};Data Source={ApiDatainfo.mysqlUrl};Port={ApiDatainfo.mysqlPost};UserId={ApiDatainfo.mysqlUser};Password={ApiDatainfo.mysqlPwd};Charset=utf8mb4;TreatTinyAsBoolean=false;Allow User Variables=True";
        try
        {
            string query = "";
            if (!string.IsNullOrEmpty(med_type))
            {
                //如果医疗类别为11普通门诊，则判断处方单上的药品是否在处方内的 西药前18位编码一致，中成药前15位编码一致;普门外的处方强制一致
                if (med_type == "11" && med_list_codg.Substring(0, 1) == "X")
                {
                    query =
                        @"SELECT count(*) FROM fsi_prescription_detail a  LEFT JOIN fsi_prescription b ON a.auth_rxno = b.auth_rxno  WHERE b.hi_rxno = @hi_rxno AND LEFT(a.med_list_codg, 18) = LEFT(@med_list_codg, 18)";
                }
                else if (med_type == "11" && med_list_codg.Substring(0, 1) == "Z")
                {
                    query =
                        @"SELECT count(*) FROM fsi_prescription_detail a  LEFT JOIN fsi_prescription b ON a.auth_rxno = b.auth_rxno  WHERE b.hi_rxno = @hi_rxno AND LEFT(a.med_list_codg, 15) = LEFT(@med_list_codg, 15)";
                }
                else
                {
                    query =
                        @"SELECT count(*) FROM fsi_prescription_detail a  LEFT JOIN fsi_prescription b ON a.auth_rxno = b.auth_rxno  WHERE b.hi_rxno = @hi_rxno AND a.med_list_codg = @med_list_codg";
                }
            }
            else
            {
                query =
                    @"SELECT count(*) FROM fsi_prescription_detail a  LEFT JOIN fsi_prescription b ON a.auth_rxno = b.auth_rxno  WHERE b.hi_rxno = @hi_rxno AND a.med_list_codg = @med_list_codg";
            }

            var parameter = new List<MySqlParameter>
            {
                new MySqlParameter("@hi_rxno", rxno),
                new MySqlParameter("@med_list_codg", med_list_codg),
            };
            int count = await MySqlHelper.ExecuteScalarAsync<int>(connectionString, query, parameter);
            if (count < 1)
            {
                return false;
            }

            return true;
        }
        catch (Exception ex)
        {
            LogHelper.Error(
                $"[DrugStoreCommonService.VerifyPrescriptionDrugs]处方药品校验异常，错误内容：{ex.Message} 异常堆栈{ex.StackTrace}");
            throw;
        }
    }
    /// <summary>
    /// 新增人员累计费用
    /// </summary>
    /// <param name="psn_no">人员编号</param>
    /// <param name="cum_type_code">费用代码</param>
    /// <param name="year">年份</param>
    /// <param name="cum">费用</param>
    /// <param name="cum_ym"></param>
    /// <param name="insutype">险种类别</param>
    /// <param name="transaction">事务</param>
    /// <returns></returns>
    public async Task<bool> InsertQueryfixmedinspracpsnsum(string psn_no, string cum_type_code,string year, decimal cum,string cum_ym,string insutype, MySqlTransaction transaction = null)
    {
        string connectionString =
            $"Database={ApiDatainfo.mysqlDatabase};Data Source={ApiDatainfo.mysqlUrl};Port={ApiDatainfo.mysqlPost};UserId={ApiDatainfo.mysqlUser};Password={ApiDatainfo.mysqlPwd};Charset=utf8mb4;TreatTinyAsBoolean=false;Allow User Variables=True";
        try
        {
            string query = "INSERT INTO fsi_queryfixmedinspracpsnsum  VALUES (@psn_no,@cum_type_code,@year,@cum,@cum_ym,@insutype)";
            
            var parameter = new List<MySqlParameter>
            {
                new MySqlParameter("@psn_no", psn_no),
                new MySqlParameter("@cum_type_code", cum_type_code),
                new MySqlParameter("@year", year),
                new MySqlParameter("@cum", cum),
                new MySqlParameter("@cum_ym", cum_ym),
                new MySqlParameter("@insutype", insutype)
            };
            await MySqlHelper.ExecuteNonQueryAsync(connectionString, query, parameter, transaction);
            return true;
        }
        catch (Exception ex)
        {
            LogHelper.Error(
                $"[DrugStoreCommonService.InsertQueryfixmedinspracpsnsum]人员费用累计新增异常，错误内容：{ex.Message} 异常堆栈{ex.StackTrace}");
            throw;
        }
    }
}